package savet.gui.tabelas;

import java.util.List;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import org.openswing.swing.mdi.client.InternalFrame;
import org.openswing.swing.mdi.client.MDIFrame;
import savet.SAVETFachada;
import savet.entidades.Empregador;
import savet.entidades.Lote;
import savet.gui.dialogos.DialogoEmpregador;
import savet.util.JOptionUtil;
import savet.util.ListaTrabalhadores;
import savet.util.LoteUtil;

/**
 *
 * @author Adisson Marinho
 */
public class GuiEdicaoLote extends InternalFrame {

    /** Creates new form GuiSelecaoEmpregador */
    public GuiEdicaoLote() {
        initComponents();
        carregarLoteAtual();
        addInternalFrameListener(new InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                LoteUtil util = LoteUtil.getInstance();
                util.resetarLote();
            }

        });
    }

    public final void carregarLoteAtual() {
        Lote loteAtual = LoteUtil.getInstance().getLoteAtual();
        if (loteAtual != null) {
            lote = loteAtual;
            txtNomeAuditor.setText(lote.getNomeAuditor());
            txtCarteira.setText(lote.getNumeroCarteira());
            model.setEmpregadores(lote.getEmpregadores());
        } else {
            lote = new Lote();
            LoteUtil.getInstance().setLoteAtual(lote);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        model = new savet.gui.modelos.EmpregadorTableModel();
        lote = new savet.entidades.Lote();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNomeAuditor = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtCarteira = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableEmpregadores = new javax.swing.JTable();
        insertButton = new org.openswing.swing.client.InsertButton();
        deleteButton = new org.openswing.swing.client.DeleteButton();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblInfo = new javax.swing.JLabel();
        editButton = new org.openswing.swing.client.EditButton();
        btnAuditar = new javax.swing.JButton();

        setTitle("Lote de empregadores");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados do lote"));

        jLabel1.setText("Nome do audidor*");

        jLabel2.setText("Número da CIF");

        tableEmpregadores.setModel(model);
        jScrollPane1.setViewportView(tableEmpregadores);

        insertButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertButtonActionPerformed(evt);
            }
        });

        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.setToolTipText("Salvar este lote em arquivo");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblInfo.setFont(new java.awt.Font("Tahoma", 0, 10));
        lblInfo.setForeground(new java.awt.Color(255, 0, 0));

        btnAuditar.setText("Auditar");
        btnAuditar.setToolTipText("Auditar um empregador da tabela acima");
        btnAuditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAuditarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                        .addGap(236, 236, 236)
                        .addComponent(btnCancelar)
                        .addGap(18, 18, 18)
                        .addComponent(btnAuditar)
                        .addGap(18, 18, 18)
                        .addComponent(btnSalvar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNomeAuditor, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCarteira, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 631, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(insertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(editButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNomeAuditor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtCarteira, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(insertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnSalvar)
                        .addComponent(btnAuditar)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertButtonActionPerformed
        DialogoEmpregador de = new DialogoEmpregador(null, true);
        de.setVisible(true);
        Empregador empregador = de.getEmpregador();
        if (empregador != null) {
            System.out.println("Adicionando empregador " + empregador);
            model.adicionarEmpregador(empregador);
        }
}//GEN-LAST:event_insertButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int selectedRow = tableEmpregadores.getSelectedRow();
        model.removerEmpregador(selectedRow);
}//GEN-LAST:event_deleteButtonActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        LoteUtil loteUtil = LoteUtil.getInstance();
        if (validarCampos()) {
            lote.setNomeAuditor(txtNomeAuditor.getText());
            lote.setNumeroCarteira(txtCarteira.getText());
            List<Empregador> empregadores = model.getEmpregadores();
            lote.setEmpregadores(empregadores);

            loteUtil.salvarArquivoLote();
        } else {
            JOptionUtil.showWarningMessage("Sem dados suficientes para salvar...", "Opps");
        }
}//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        int result = JOptionUtil.yesNoOption("Deseja realmente cancelar a operação?", "Cancelamento");
        if (JOptionUtil.isYesResult(result)) {
            dispose();
        }
}//GEN-LAST:event_btnCancelarActionPerformed

    private void btnAuditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAuditarActionPerformed
        if (LoteUtil.getInstance().getContadorAuditoria() == 0) {

            int indexSelected = tableEmpregadores.getSelectedRow();
            if (indexSelected != -1) {
                ListaTrabalhadores listaTrabalhadores = ListaTrabalhadores.getInstance();
                LoteUtil loteUtil = LoteUtil.getInstance();

                Empregador empregador = model.getEmpregador(indexSelected);

                loteUtil.setEmpregadorAtual(empregador);
                listaTrabalhadores.atualizarTrabalhadores(empregador.getTrabalhadores());

                SAVETFachada clientFacade = (SAVETFachada) MDIFrame.getClientFacade();
                GuiSAVET guiSavet = clientFacade.getGuiSavet();
                guiSavet.setTrabalhadores(listaTrabalhadores.getTrabalhadores());
                LoteUtil.getInstance().incrementarContadorAuditoria();
            } else {
                String t = "Aten\u00e7\u00e3o";
                String msg = "Selecione pelo menos um empregador da tabela. Caso n\u00e3o haja nenhum, cadastre.";

                JOptionUtil.showWarningMessage(msg, t);
            }
        } else {
            String t = "Aten\u00e7\u00e3o";
            String msg = "N\u00e3o e possível mais de uma auditoria simultaneamente.";

            JOptionUtil.showWarningMessage(msg, t);
        }
    }//GEN-LAST:event_btnAuditarActionPerformed

    private boolean validarCampos() {
        return !txtNomeAuditor.getText().isEmpty() && !txtCarteira.getText().isEmpty()
                && !model.isEmpty();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAuditar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSalvar;
    private org.openswing.swing.client.DeleteButton deleteButton;
    private org.openswing.swing.client.EditButton editButton;
    private org.openswing.swing.client.InsertButton insertButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblInfo;
    private savet.entidades.Lote lote;
    private savet.gui.modelos.EmpregadorTableModel model;
    private javax.swing.JTable tableEmpregadores;
    private javax.swing.JTextField txtCarteira;
    private javax.swing.JTextField txtNomeAuditor;
    // End of variables declaration//GEN-END:variables
}
